package com.mr.cai.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cai.mr.lib.utils.LogInfo;
import com.mr.cai.main.R;
import com.mr.cai.main.activity.base.MrCaiBaseActivity;
import com.mr.cai.main.bean.MrCaiPublicStatusBean;
import com.mr.cai.main.httpApi.MrCaiHttpApi;
import com.mr.cai.main.parse.MrCaiPublicStatusBeanParse;
import com.mr.cai.main.utils.CommonCoreUtil;
import com.mr.cai.main.view.LineEditText;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by hai8108 on 16/2/8.
 */
public class RegisterActivity extends MrCaiBaseActivity {
    private ProgressBar pb_loaing;
    private View backView;
    private TextView titleView;
    private LineEditText registerMobileNum, registerPwd, registerCode, registerInviteCode;
    private TextView checkTv;
    private TextView registerMrCaiCheckTv, registerEmailTv;
    private TextView registerCodeRequestTv, registerSubmit;
    private TextView mrCaiCountLogin;

    public static void launchActivity (Activity activity) {
        Intent intent = new Intent(activity, RegisterActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_layout);
        findView();
        initClickAction();
    }

    private void findView () {
        View topView = findViewById(R.id.top_view);
        pb_loaing = (ProgressBar) findViewById(R.id.pb_loaing);
        backView = topView.findViewById(R.id.pub_top_left);
        titleView = (TextView) topView.findViewById(R.id.pub_top_mid);
        titleView.setText(R.string.register_txt);

        registerMobileNum = (LineEditText) findViewById(R.id.register_mobile_num);
        registerPwd = (LineEditText) findViewById(R.id.register_pwd_set);
        registerCode = (LineEditText) findViewById(R.id.register_auth_code);
        registerInviteCode = (LineEditText) findViewById(R.id.register_invite_num);
        registerCodeRequestTv = (TextView) findViewById(R.id.register_auth_code_request);

        registerPwd.setBottomLineColor(R.color.color_main_sub_white_gray);
        registerCode.setBottomLineColor(R.color.color_main_sub_white_gray);
        registerInviteCode.setBottomLineColor(R.color.color_main_sub_white_gray);

        checkTv = (TextView) findViewById(R.id.register_check_iv);
        registerMrCaiCheckTv = (TextView) findViewById(R.id.register_agree_auth_des);
        registerMrCaiCheckTv.setText(Html.fromHtml(getString(R.string.register_agree_auth)
                +"<u>"+getString(R.string.register_agree_auth_des) + "</u>"));
        registerEmailTv = (TextView) findViewById(R.id.register_with_email);
        registerSubmit = (TextView) findViewById(R.id.login_register);
        mrCaiCountLogin = (TextView) findViewById(R.id.login_with_mr_cai_count);
    }

    private Subscription stopMePlease;
    private Subscription registerCodeReqSub;
    private Subscription registerSubscription;
    private final int REQUEST_CODE_RESET_TIME = 99;

    private void setRegisterCodeClickAction () {
        stopMePlease = Observable.interval(1, TimeUnit.SECONDS).take(REQUEST_CODE_RESET_TIME)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted () {
                        stopMePlease.unsubscribe();
                        registerCodeRequestTv.setEnabled(true);
                        registerCodeRequestTv.setText(R.string.register_auth_code_reset);
                    }

                    @Override
                    public void onError (Throwable e) {
                    }

                    @Override
                    public void onNext (Long number) {
                        registerCodeRequestTv.setText("\t" + (REQUEST_CODE_RESET_TIME - number
                                .intValue()) + " S " + "\t");
                        LogInfo.log("haitian", "number = " + number);
                    }
                });
    }

    private void getRegisterCodeMsg (String mobileNum) {
        Observable<MrCaiPublicStatusBean> authCodeObservable = MrCaiHttpApi.requestAuthcode
                (mobileNum, new MrCaiPublicStatusBeanParse());
        registerCodeReqSub = authCodeObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MrCaiPublicStatusBean>() {
                    @Override
                    public void onStart () {
                        CommonCoreUtil.showToast(R.string.request_code_send_txt);
                    }

                    @Override
                    public void onCompleted () {
                    }

                    @Override
                    public void onError (Throwable e) {
                        CommonCoreUtil.showToast(R.string.request_code_send_error);
                        registerCodeRequestTv.setEnabled(true);
                        registerCodeRequestTv.setText(R.string.register_auth_code_reset);
                    }

                    @Override
                    public void onNext (MrCaiPublicStatusBean mMrCaiPublicStatusBean) {
                        if (mMrCaiPublicStatusBean != null) {
                            if (!TextUtils.isEmpty(mMrCaiPublicStatusBean.getAuthCode())) {
                                registerCode.setText(mMrCaiPublicStatusBean.getAuthCode());
                            } else {
                                CommonCoreUtil.showToast(mMrCaiPublicStatusBean.getMsg());
                            }
//                            stopMePlease.unsubscribe();
//                            registerCodeRequestTv.setEnabled(true);
//                            registerCodeRequestTv.setText(R.string.register_auth_code_reset);
                        }
                    }
                });
    }

    private boolean isAgree = false;

    private void initClickAction () {
        CommonCoreUtil.setClickAction(checkTv, new Action1() {
            @Override
            public void call (Object o) {
                if (!isAgree) {
                    isAgree = true;
                    checkTv.setBackgroundResource(R.drawable.mr_cai_check_on);
                } else {
                    isAgree = false;
                    checkTv.setBackgroundResource(R.drawable.mr_cai_check_off);
                }
            }
        });
        CommonCoreUtil.setClickAction(mrCaiCountLogin, new Action1() {
            @Override
            public void call (Object o) {
                finish();
            }
        });
        CommonCoreUtil.setClickAction(registerMrCaiCheckTv, new Action1() {
            @Override
            public void call (Object o) {
                AgreementActivity.launchActivity(RegisterActivity.this);
            }
        });
        CommonCoreUtil.setClickAction(backView, new Action1() {
            @Override
            public void call (Object o) {
                finish();
            }
        });
        CommonCoreUtil.setClickAction(registerCodeRequestTv, new Action1() {
            @Override
            public void call (Object o) {
                if (CommonCoreUtil.judgeRegxEmailAndMobile(registerMobileNum.getEditableText().toString())) {
                    registerCodeRequestTv.setEnabled(false);
                    getRegisterCodeMsg(registerMobileNum.getEditableText().toString());
                    setRegisterCodeClickAction();
                }
            }
        });
        CommonCoreUtil.setClickAction(registerSubmit, new Action1() {
            @Override
            public void call (Object o) {
                if (judgeInput()) {
                    String code = registerCode.getEditableText().toString();
                    if (TextUtils.isEmpty(code)) {
                        CommonCoreUtil.showToast(R.string.register_code_is_null);
                        return;
                    }
                    if (!isAgree) {
                        CommonCoreUtil.showToast(R.string.register_agreement_null);
                        return;
                    }
                    {
                        requestRegister(registerMobileNum.getEditableText().toString(),
                                registerPwd.getEditableText().toString(),
                                registerCode.getEditableText().toString());
                    }
                }
            }
        });
    }

    private void requestRegister (String mobileNum, String pwd, String authCode) {
        Observable<MrCaiPublicStatusBean> authCodeObservable = MrCaiHttpApi.requestRegister
                (mobileNum, pwd, authCode, new MrCaiPublicStatusBeanParse());
        registerSubscription = authCodeObservable.observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call () {
                        pb_loaing.setVisibility(View.VISIBLE);
                    }
                })
                .subscribe(new Subscriber<MrCaiPublicStatusBean>() {
                    @Override
                    public void onCompleted () {
                        pb_loaing.setVisibility(View.GONE);
                    }
                    @Override
                    public void onError (Throwable e) {
                        pb_loaing.setVisibility(View.GONE);
                        CommonCoreUtil.showToast(R.string.data_request_fail);
                    }
                    @Override
                    public void onNext (MrCaiPublicStatusBean mMrCaiPublicStatusBean) {
                        if (mMrCaiPublicStatusBean != null && mMrCaiPublicStatusBean.isResult()
                                && mMrCaiPublicStatusBean.getCode() == 1) {
                            CommonCoreUtil.showToast(R.string.register_success_txt);
                            finish();
                        } else {
                            if (mMrCaiPublicStatusBean != null) {
                                CommonCoreUtil.showToast(mMrCaiPublicStatusBean.getMsg());
                            } else {
                                CommonCoreUtil.showToast(R.string.public_loading_net_err_txt);
                            }
                        }
                    }
                });
    }

    private boolean judgeInput () {
        String newEmail = registerMobileNum.getEditableText().toString();
        String newPassword = registerPwd.getEditableText().toString();
        if (!CommonCoreUtil.judgeRegxEmailAndMobile(newEmail)) {
            return false;
        }
        boolean passValid = !TextUtils.isEmpty(newPassword) && newPassword.length() >= 6;
        if (!passValid) {
            CommonCoreUtil.showToast(R.string.pwd_length_error);
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy () {
        super.onDestroy();
        CommonCoreUtil.hideSoftInput(registerMobileNum);
        CommonCoreUtil.hideSoftInput(registerPwd);
        CommonCoreUtil.hideSoftInput(registerCode);
        CommonCoreUtil.hideSoftInput(registerInviteCode);
        if (registerCodeReqSub != null) {
            registerCodeReqSub.unsubscribe();
            registerCodeReqSub = null;
        }
        if (registerSubscription != null) {
            registerSubscription.unsubscribe();
            registerSubscription = null;
        }
        if (stopMePlease != null) {
            stopMePlease.unsubscribe();
            stopMePlease = null;
        }
    }
}
